package com.futao.support;

import com.futao.view.model.ErrorMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author futao
 * Created on 18-6-5-下午12:52.
 * <p>
 * 统一异常处理类
 * <p>
 * 使用@ControllerAdvice定义统一的异常处理类
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";

    /**
     * 使用@ExceptionHandler用来定义函数针对的异常类型
     *
     * @param httpServletRequest
     * @param e
     * @return
     */
//    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandle(HttpServletRequest httpServletRequest, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e);
        modelAndView.addObject("url", httpServletRequest.getRequestURL());
        modelAndView.addObject("info", e.getMessage());
        System.out.println("-----------\n" + e.getMessage());
        modelAndView.setViewName(DEFAULT_ERROR_VIEW);
        return modelAndView;
    }

    /**
     * 处理MyException的异常
     *
     * @param httpServletRequest
     * @param e
     * @return
     */
//    @ExceptionHandler(value = MyException.class)
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ErrorMessage<String> jsonErrorHandle(HttpServletRequest httpServletRequest, Exception e) {
        ErrorMessage<String> errorMessage = new ErrorMessage<>();
        errorMessage.setMessage(e.getMessage());
        errorMessage.setStacktrace(Arrays.toString(e.getStackTrace()));
        errorMessage.setCode(ErrorMessage.ERROR);
        errorMessage.setData("Some data");
        errorMessage.setUrl(httpServletRequest.getRequestURL().toString());
        log.error("Exception message: " + e.getMessage());
        log.error("stackTrace: " + Arrays.toString(e.getStackTrace()));
        return errorMessage;
    }
}